package com.xzc.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.seckill.exception.GlobalException;
import com.xzc.seckill.mapper.UserMapper;
import com.xzc.seckill.pojo.User;
import com.xzc.seckill.service.UserService;
import com.xzc.seckill.util.CookieUtil;
import com.xzc.seckill.util.MD5Util;
import com.xzc.seckill.util.UUIDUtil;
import com.xzc.seckill.util.ValidatorUtil;
import com.xzc.seckill.vo.LoginVo;
import com.xzc.seckill.vo.RespBean;
import com.xzc.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 徐生
 * @version 1.0
 * Date 2024/3/31 20:48
 * Description: UserServiceImpl
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //完成用户的登录校验
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //判断是手机号码和id否为空
//        if (!StringUtils.hasText(mobile) || !StringUtils.hasText(password)) {
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
        //检验手机号码是否合格
//        if (!ValidatorUtil.isMobile(mobile)) {
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }

        //查询数据库，判断用户是否存在
        User user = userMapper.selectById(mobile);
        if (user == null) {
            //return RespBean.error(RespBeanEnum.LOGIN_ERROR);//处理异常方式一
            throw  new GlobalException(RespBeanEnum.LOGIN_ERROR);//处理异常方式二
        }

        //用户存在则比较密码
        //注意，从loginVo取出来的密码是中间密码（即客户端经过一次加密加盐处理的密码）
        if (!MD5Util.midPassToDBPass(password, user.getSlat()).equals(user.getPassword())) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //用户登录成功，给每个生成ticket（唯一）
        String ticket = UUIDUtil.uuid();
        //将登录成功的用户保存到session
//        request.getSession().setAttribute(ticket, user);

        //为了实现分布式Session，把登录的用户存放到Redis
        redisTemplate.opsForValue().set("user:"+ticket,user);
        //将ticket保存到cookie
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        //这里我们需要返回userTicket
        return RespBean.success(ticket);
    }

    //根据Cookie（ticket）获取用户信息
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.hasText(userTicket)) {
            return null;
        }
        //根据userTicket到Redis获取user
        User user = (User)redisTemplate.opsForValue().get("user:" + userTicket);
        //如果用户不为null，就重新设置cookie（防止过期），根据业务需求来的
        if (user != null) {
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }

    //更新密码——假定password以明文方式传入（只为测试）
    public RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = getUserByCookie(userTicket, request, response);
        if (user == null){//抛出异常
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        //设置密码
        user.setPassword(MD5Util.inputPassToDBPass(password,user.getSlat()));
        int i = userMapper.updateById(user);
        if (i == 1){//更行成功
            //删除该用户再Redis中的数据
            redisTemplate.delete("user:" + userTicket);
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }
}
